<template>
  <div class="orders-container">
    <div class="header">
      <h2>订单管理</h2>
      <!-- <div class="stats">
        <el-statistic title="总订单数" :value="total" />
        <el-statistic title="今日订单" :value="todayOrders" />
        <el-statistic title="待处理订单" :value="pendingOrders" />
      </div> -->
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.code" placeholder="请输入订单号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="交易状态">
          <el-select v-model="searchForm.tradeStatus" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="未完成" :value="false" />
            <el-option label="已完成" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="orders" stripe style="width: 100%" :row-key="(row) => row.id">
        <el-table-column prop="id" label="Id" width="80" />
        <el-table-column prop="code" label="订单号" width="180" />
        <el-table-column prop="detail" label="订单备注" width="180" />
        <el-table-column prop="userId" label="买家ID" width="80" />
        <el-table-column prop="productId" label="商品ID" width="80" />
        <el-table-column prop="buyPrice" label="购买价格" width="100" />
        <el-table-column prop="tradeStatus" label="交易状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.tradeStatus)">
              {{ getStatusText(row.tradeStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tradeTime" label="交易时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <!-- <el-button 
              v-if="row.tradeStatus === 1" 
              size="small" 
              type="primary" 
              @click="handleShip(row)"
            >
              发货
            </el-button> -->
            <!-- <el-button 
              v-if="row.status === 5" 
              size="small" 
              type="warning" 
              @click="handleRefund(row)"
            >
              退款
            </el-button> -->
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="700px" :before-close="handleDetailClose">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.code }}</el-descriptions-item>
          <el-descriptions-item label="交易时间">{{ formatDate(currentOrder.tradeTime) }}</el-descriptions-item>
          <el-descriptions-item label="订单备注">{{ currentOrder.detail }}</el-descriptions-item>
          <el-descriptions-item label="买家ID">{{ currentOrder.userId }}</el-descriptions-item>
          <el-descriptions-item label="商品ID">{{ currentOrder.productId }}</el-descriptions-item>
          <el-descriptions-item label="购买价格">¥{{ currentOrder.buyPrice }}</el-descriptions-item>
          <el-descriptions-item label="交易状态">
            <el-tag :type="getStatusType(currentOrder.tradeStatus)">
              {{ getStatusText(currentOrder.tradeStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <!-- <el-dialog
      v-model="shipVisible"
      title="订单发货"
      width="500px"
    >
      <el-form :model="shipForm" label-width="100px">
        <el-form-item label="快递公司">
          <el-select v-model="shipForm.expressCompany" placeholder="请选择快递公司">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="申通快递" value="STO" />
            <el-option label="韵达速递" value="YD" />
            <el-option label="百世快递" value="HTKY" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确认发货</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Order } from '@/types'
import { formatDate } from '@/utils/date'

// 响应式数据
const loading = ref(false)
const orders = ref<Order[]>([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
// const todayOrders = ref(15)
// const pendingOrders = ref(8)
const detailVisible = ref(false)
const currentOrder = ref<Order | null>(null)

// 搜索表单
const searchForm = reactive({
  code: '',
  tradeStatus: undefined as boolean | undefined,
})

// // 发货表单
// const shipForm = reactive({
//   expressCompany: '',
//   trackingNo: ''
// })

// 获取订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // await new Promise(resolve => setTimeout(resolve, 500))
    const res = await request.get('/orders/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        code: searchForm.code,
        tradeStatus: searchForm.tradeStatus
      }
    }) as any
    // 确保数据是数组
    const dataArray = Array.isArray(res.data.data) ? res.data.data : []
    orders.value = dataArray
    total.value = res.data.allRow || 0

 
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadOrders()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    code: '',
    tradeStatus: undefined,
  })
  currentPage.value = 1
  loadOrders()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadOrders()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadOrders()
}

// 查看订单详情
const handleView = (row: Order) => {
  currentOrder.value = row
  detailVisible.value = true
}

// // 发货
// const handleShip = (row: Order) => {
//   currentOrder.value = row
//   shipVisible.value = true
// }

// 确认发货
// const confirmShip = async () => {
//   if (!shipForm.expressCompany || !shipForm.trackingNo) {
//     ElMessage.warning('请填写完整的发货信息')
//     return
//   }

//   try {
//     // 模拟发货操作
//     await new Promise(resolve => setTimeout(resolve, 500))
//     ElMessage.success('发货成功')
//     shipVisible.value = false
//     Object.assign(shipForm, { expressCompany: '', trackingNo: '' })
//     loadOrders()
//   } catch (error) {
//     ElMessage.error('发货失败')
//   }
// }

// 退款
// const handleRefund = async (row: Order) => {
//   try {
//     await ElMessageBox.confirm(
//       `确定要为订单"${row.orderNo}"退款吗？`,
//       '确认退款',
//       {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//     )

//     // 模拟退款操作
//     await new Promise(resolve => setTimeout(resolve, 500))
//     ElMessage.success('退款成功')
//     loadOrders()
//   } catch (error) {
//     if (error !== 'cancel') {
//       ElMessage.error('退款失败')
//     }
//   }
// }

// 删除订单
const handleDelete = async (row: Order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单"${row.code}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 删除操作
    // await new Promise(resolve => setTimeout(resolve, 500))
    await request.delete('/orders/' + row.id)
    ElMessage.success('删除成功')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentOrder.value = null
}

// 获取状态类型
const getStatusType = (tradeStatus: boolean) => {
  switch (tradeStatus) {
    case false: return 'warning'
    case true: return 'success'
    default: return 'warning'
  }
}

// 获取状态文本
const getStatusText = (tradeStatus: boolean) => {
  switch (tradeStatus) {
    case false: return '未完成'
    case true: return '已完成'
    default: return '未完成'
  }
}

// 初始化
onMounted(() => {
  // 确保数据是数组
  if (!Array.isArray(orders.value)) {
    orders.value = []
  }
  loadOrders()
})
</script>

<style scoped lang="scss">
.orders-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-color;
    }

    .stats {
      display: flex;
      gap: 20px;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }

  .amount {
    color: $danger-color;
    font-weight: bold;
  }

  .product-info {
    display: flex;
    align-items: center;

    .product-details {
      .product-name {
        font-weight: bold;
        color: $text-color;
        margin-bottom: 4px;
      }

      .product-price {
        color: $text-color-light;
        font-size: 12px;
      }
    }
  }
}

.order-detail {

  .address-info,
  .remark-info {
    margin-top: 20px;

    h4 {
      margin: 0 0 10px 0;
      color: $text-color;
      font-size: 14px;
    }

    p {
      margin: 0;
      color: $text-color-regular;
      line-height: 1.6;
    }
  }
}
</style>